<?php

namespace App\Http\Controllers\Api;

use App\Http\Requests\Api\ProductsRequest;
use App\Models\Product;
use App\Transformers\ProductTransformer;
use App\Transformers\ScheduleTransformer;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class ProductsController extends Controller
{
    public function index(Request $request)
    {
        $title = $request->get('title');

        $price = $request->get('price');

        $where = $request->only([
            'province', 'city', 'district', 'recommended', 'shop_id',
        ]);

        $limit = $request->get('limit');

        $query = Product::where('is_show', true)
            ->where(function ($query) use ($title, $price) {
                if ($title) {
                    $query->where('title', 'like', '%' . $title . '%');
                }
                if ($price && strpos($price, '-')) {
                    $query->whereBetween('price', explode('-', $price));
                }
                if ($price && !strpos($price, '-')) {
                    $query->whereBetween('price', [0, (double)$price]);
                }
            })
            ->where($where)->orderBy('recommended', 'desc')->orderBy('sell_amount', 'desc')->orderBy('sort', 'desc');

        if ($limit) {
            $data = $query->limit($limit)->get();

            return $this->response->collection($data, new ProductTransformer(['id', 'title', 'image', 'shop_name', 'price']));
        } else {
            $data = $query->paginate();

            return $this->response->paginator($data, new ProductTransformer(['id', 'title', 'image', 'shop_name', 'price']));
        }
    }

    public function show($id)
    {
        $data = Product::find($id);

        if (!$data) {
            $this->response->error(trans('api.not_exists'), 200);
        }

        //增加浏览量
        $data->increment('view_amount');

        return $this->response->item($data, new ProductTransformer());
    }

    public function create(ProductsRequest $request)
    {
        $data = $request->only([
            'title', 'subtitle', 'image', 'contact_phone', 'content', 'pictures',
            'service_time', 'is_show', 'province', 'city', 'district', 'address', 'longitude', 'latitude',
        ]);

        $schedules = $request->get('schedules');

        $data['shop_id'] = $this->user->shop->id;

        DB::transaction(function () use ($data, $schedules) {
            try {
                $product = Product::create($data);

                if ($schedules) {
                    foreach ($schedules as $time) {
                        $product->schedules()->create($time);
                    }
                }

            } catch ( \Exception $exception ) {
                $this->response->error(trans('api.save_failed'), '200');
            }
        });

        return response()->json(['message' => trans('api.save_succeed'), 'code' => 1, 'status' => true, 'data' => ''], 200);
    }

    public function edit(ProductsRequest $request)
    {
        $id = $request->get('id');

        $data = $request->only([
            'title', 'shop_id', 'subtitle', 'image', 'contact_phone', 'content', 'service_time', 'sort',
            'is_show', 'province', 'city', 'district', 'address', 'longitude', 'latitude',
        ]);

        $product = Product::find($id);

        $this->authorize('update', $product);//判断是否有修改权限

        if (!$product) {
            $this->response->error(trans('api.not_exists'), 200);
        }

        $res = $product->fill($data)->save();

        if ($res) {
            return response()->json(['message' => trans('api.update_succeed'), 'code' => 1, 'status' => true, 'data' => ''], 200);
        } else {
            return response()->json(['message' => trans('api.update_failed'), 'code' => 0, 'status' => false], 200);
        }
    }

    public function myProducts(Request $request)
    {
        $limit = $request->get('limit');

        $query = Product::where('shop_id', $this->user->shop->id)
            ->orderBy('recommended', 'desc')
            ->orderBy('sell_amount', 'desc')
            ->orderBy('sort', 'desc');

        if ($limit) {
            $data = $query->limit($limit)->get();

            return $this->response->collection($data, new ProductTransformer(['id', 'title', 'image', 'shop_name', 'price', 'is_show']));
        } else {
            $data = $query->paginate();

            return $this->response->paginator($data, new ProductTransformer(['id', 'title', 'image', 'shop_name', 'price', 'is_show']));
        }
    }
}
